package cn.momoshenchi.search.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/4/28 - 13:46
 */
@Service
public class OssService
{
    @Resource
    private OSSClient ossClient;

    @Value("${alibaba.cloud.oss.endpoint}")
    private  String endpoint;

    private  String bucket = "gulimail-momoshenchi";

    @Value("${alibaba.cloud.access-key}")
    private  String accessKey;

    public Map<String,String> policy() throws UnsupportedEncodingException
    {
        String host="https://"+bucket+"."+endpoint;
        String callbackUrl="";
        String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        long exp=30;
        long expEnd=System.currentTimeMillis()+exp*30;
        Instant instant= Instant.ofEpochMilli(expEnd);

        PolicyConditions  policyConditions=new PolicyConditions();
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        String postPolicy = ossClient.generatePostPolicy(Date.from(instant), policyConditions);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        Map<String,String>respMap=new HashMap<>();
        respMap.put("accessid", accessKey);
        respMap.put("policy", encodedPolicy);
        respMap.put("signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", host);
        respMap.put("expire", String.valueOf(expEnd / 1000));
        // respMap.put("expire", formatISO8601Date(expiration));


        return  respMap;

    }

}